package org.mini.command
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.mini.command.AbstractSequenceCommand;
	import org.mini.core.LevelView;
	import org.mini.core.SiteStructure;
	import org.mini.core.mini_internal;
	
	use namespace mini_internal;
	
	public class SiteSetupCommand extends AbstractSequenceCommand
	{
		private var _path:String;
		private var _loader:URLLoader;
		
		public function SiteSetupCommand(path:String)
		{
			super();
			
			_path=path;
		}
		
		override public function execute():void
		{
			_loader=new URLLoader();
			_loader.addEventListener(Event.COMPLETE,onCompleteHandler);
			_loader.addEventListener(IOErrorEvent.IO_ERROR,onErrorHandler);
			_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onErrorHandler);
			_loader.load(new URLRequest(_path));
		}
		
		private function onCompleteHandler(e:Event):void
		{
			_loader.removeEventListener(Event.COMPLETE,onCompleteHandler);
			_loader.removeEventListener(IOErrorEvent.IO_ERROR,onErrorHandler);
			_loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onErrorHandler);
			
			try{
				var xml:XML=XML((e.currentTarget as URLLoader).data);
				LevelView.init(uint(xml.@layers));
				SiteStructure.setup(xml);
			}
			catch(error:Error){
				trace("SiteSetupCommand parse XML error!");
			}
			
			try{
				_loader.data=null;
				_loader=null;
			}
			catch(error:Error){
				trace("SiteSetupCommand _loader error!");
			}
			
			executeNextCommand();
		}
		
		private function onErrorHandler(e:Event):void
		{
			throw new Error("Application can't find site xml from "+_path);
		}
	}
}